import json

import websocket
from threading import Thread
from websocket_information.WSServiceImpl import instruction_impl

cameraId = 'CentralEquipment'
wsPath = 'ws://58.34.215.18:2015/websocket/'
# wsPath = 'ws://127.0.0.1:2015/websocket/'


def on_message(ws, message):
    print(message)
    if message is not None:
        str(message)
        mes = json.loads(message)
        code = mes['code']
        uuid = mes['uuid']
        message = mes['message']
        instruction_impl(code=code, uuid=uuid, message=message, webs=ws)


def on_error(ws, error):
    print(error)


def on_close(ws):
    print("### closed ###")
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(wsPath + cameraId,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever()


def on_open(ws):
    print("连接成功")
    on_send(ws, "连接成功")


def on_send(ws, message):
    ws.send(message)


class ConfigWebSocket(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        websocket.enableTrace(True)
        ws = websocket.WebSocketApp(wsPath + cameraId,
                                    on_message=on_message,
                                    on_error=on_error,
                                    on_close=on_close)
        ws.on_open = on_open
        ws.run_forever()


def configWS():
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(wsPath + cameraId,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever()
